﻿using System;
using Slippor.Douban.Radio.Assist;
using Slippor.Douban.Radio.Handler;
using Timer = System.Threading.Timer;
using Slippor.Common.PluginFramework;

namespace AutoFavHandlerPlugin
{
    public class AutoFavHandler : IHandler
    {
        public const string Key = "AutoFav";

        private readonly Timer _timer;
        private Song _currentSong = Song.DefaultSong;

        private TimeSpan _interval = AutoFavConfig.DefaultInterval;
        public TimeSpan Interval
        {
            get { return _interval; }
            set { _interval = value; }
        }

        private readonly IPlugin _plugin;
        public AutoFavHandler(IPlugin plugin)
        {
            _timer = new Timer(AutoMakeFav);
            _plugin = plugin;
        }

        public void AutoMakeFav(object state)
        {
            _timer.Change(-1, -1);
            if (_currentSong.FaveState == FavState.UnFav)
            {
                if (_plugin != null)
                {
                    _plugin.Application.Execute((int)Command.Fav);
                }
            }
        }

        public string Name
        {
            get { return Key; }
        }

        public void Hand(Song song)
        {
            _timer.Change(-1, -1);
            if (song.FaveState == FavState.UnFav)
            {
                _currentSong = song;
                _timer.Change(_interval, TimeSpan.Zero);
            }
        }

        public void Drop(Song song)
        {
            _timer.Change(-1, -1);
            _currentSong = Song.DefaultSong;
        }
    }
}